Skip to content

New test workflow#135

Open
driedpampas wants to merge 8 commits intomainfrom
new-test-workflow
Open

New test workflow#135
driedpampas wants to merge 8 commits intomainfrom
new-test-workflow

Conversation

@driedpampas
Copy link
Copy Markdown
Member

@driedpampas driedpampas commented Apr 1, 2026

Summary by CodeRabbit

Release Notes

  • New Features

    • WebSocket JWT authentication support for secure real-time connections via query parameters and STOMP headers
    • MongoDB database integration
  • Improvements

    • Enhanced authentication enforcement for WebSocket subscriptions
    • Updated Java runtime to version 21 with improved toolchain
    • Automated testing pipeline with containerized PostgreSQL and MongoDB services
  • Chores

    • Dependency version updates for test containers

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 1, 2026

📝 Walkthrough

Walkthrough

This PR adds MongoDB integration and WebSocket JWT authentication to the application. MongoDB 7 service was added to Docker Compose with initialization support. The JWT authentication filter was refactored to extract reusable helper methods for bearer token parsing and token validation. Two new interceptor components (JwtHandshakeInterceptor and StompJwtAuthInterceptor) were introduced to authenticate WebSocket connections at the handshake and STOMP protocol layers. GitHub Actions workflows were updated to use JDK 21 and expanded with a comprehensive test workflow that runs against PostgreSQL and MongoDB service containers. Environment configuration and Gradle dependencies were updated to support MongoDB connectivity.

Changes

Cohort / File(s) Summary
MongoDB Configuration
.env.example, docker-compose.yml, src/main/resources/application.properties, src/test/java/resources/application-test.properties
Added MongoDB 7 service with initialization, volume, healthcheck, and port mapping. Updated Spring Data MongoDB URI configuration with environment variable override support.
CI/CD & Build Infrastructure
.github/workflows/build.yml, .github/workflows/test.yml, build.gradle.kts
Updated Java setup to JDK 21 (Temurin distribution). Added new test workflow with PostgreSQL 16 and MongoDB 7 service containers, health checks, test report/JaCoCo upload. Updated testcontainers dependencies.
JWT Authentication Refactoring
src/main/java/com/p2ps/auth/security/JwtAuthFilter.java
Extracted bearer token parsing (extractBearerToken) and token authentication (authenticateToken) into reusable public methods. Simplified doFilterInternal to use the new helper methods while maintaining existing error handling.
Security Configuration
src/main/java/com/p2ps/auth/security/SecurityConfig.java
Added permit-all rules for /ws/** (WebSocket) and root / path alongside existing /api/auth/** exemption.
WebSocket JWT Authentication
src/main/java/com/p2ps/config/JwtHandshakeInterceptor.java, src/main/java/com/p2ps/config/StompJwtAuthInterceptor.java
Added handshake interceptor to validate JWT tokens from query parameters and store tokens in session. Added STOMP channel interceptor to authenticate CONNECT frames using JWT from headers or session, rejecting with 401 on invalid tokens.
WebSocket Configuration Integration
src/main/java/com/p2ps/config/RoomSubscriptionInterceptor.java, src/main/java/com/p2ps/config/WebSocketConfig.java
Updated subscription interceptor to validate authenticated principal before allowing subscriptions. Integrated JWT handshake and STOMP auth interceptors into WebSocket configuration via constructor injection.
JWT Filter Unit Tests
src/test/java/com/p2ps/auth/JwtAuthFilterTest.java, src/test/java/com/p2ps/auth/security/JwtAuthFilterTest.java
Removed legacy test file. Added comprehensive JUnit 5 test suite covering bearer token extraction edge cases, token authentication success/failure scenarios, and filter chain behavior under various header/authentication states.
Security Configuration Tests
src/test/java/com/p2ps/auth/security/SecurityConfigTest.java
Added test coverage for password encoder, authentication manager provider, and CORS configuration with specific allowed origins, methods, and headers.
WebSocket Authentication Tests
src/test/java/com/p2ps/config/JwtHandshakeInterceptorTest.java, src/test/java/com/p2ps/config/StompJwtAuthInterceptorTest.java, src/test/java/com/p2ps/config/RoomSubscriptionInterceptorTest.java, src/test/java/com/p2ps/config/WebSocketConfigTest.java
Added test suites for handshake token validation (query parameter extraction, status codes), STOMP CONNECT authentication (header/session token resolution, pass-through behavior), subscription authorization (principal validation), and WebSocket config interceptor integration.

Sequence Diagram(s)

sequenceDiagram
    actor Client
    participant WebSocket as WebSocket<br/>Handshake Handler
    participant Handshake as JwtHandshakeInterceptor
    participant STOMP as STOMP Broker
    participant StompAuth as StompJwtAuthInterceptor
    participant JWT as JwtAuthFilter
    participant SecurityCtx as SecurityContextHolder

    Client->>WebSocket: Initiate WS connection<br/>(token in query param)
    WebSocket->>Handshake: beforeHandshake()
    Handshake->>Handshake: Extract token from URI
    alt Token present and enabled
        Handshake->>JWT: authenticateToken(token)
        JWT-->>Handshake: UsernamePasswordAuthenticationToken
        Handshake->>Handshake: Store token in session<br/>attributes
    end
    Handshake-->>WebSocket: Allow handshake
    
    Client->>STOMP: STOMP CONNECT<br/>(token in header/session)
    STOMP->>StompAuth: preSend() for CONNECT
    StompAuth->>StompAuth: Extract token from<br/>headers or session
    alt Token exists
        StompAuth->>JWT: authenticateToken(token)
        JWT-->>StompAuth: UsernamePasswordAuthenticationToken
        StompAuth->>STOMP: Attach auth to<br/>message user
    else Invalid token
        StompAuth->>StompAuth: Throw BadCredentialsException
    end
    StompAuth-->>STOMP: Return processed message
    
    Client->>STOMP: STOMP SUBSCRIBE
    STOMP->>STOMP: RoomSubscriptionInterceptor<br/>validates principal
    STOMP-->>Client: Allow subscription
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • Backend User Authentication & Registration #133: Introduced JwtAuthFilter and core JWT authentication logic; this PR refactors the filter with extracted helper methods (extractBearerToken, authenticateToken) that are now reused by the new WebSocket authentication interceptors.

Suggested reviewers

  • Bianca-Alexandru
🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 5.80% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'New test workflow' is vague and generic, using non-descriptive terminology that does not clearly convey the full scope of changes in the pull request. Consider a more specific title that captures the main objectives, such as 'Add MongoDB integration and update CI/CD pipeline' or 'Integrate MongoDB with WebSocket JWT authentication and test infrastructure'.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch new-test-workflow

Comment @coderabbitai help to get the list of available commands and usage tips.

@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud bot commented Apr 1, 2026

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (7)
src/main/java/com/p2ps/config/RoomSubscriptionInterceptor.java (1)

47-49: Anonymous authentication is not currently enabled in this application; this defensive check is optional.

Anonymous auth is explicitly disabled in SecurityConfig (no .anonymous() call), and StompJwtAuthInterceptor returns null when no JWT is present, so the principal remains null. The existing instanceof check on line 47 correctly rejects this case. However, adding an explicit AnonymousAuthenticationToken check is a reasonable defense-in-depth improvement to guard against future configuration changes that might enable anonymous auth without realizing the WebSocket impact.

Optional defensive improvement
 import org.springframework.security.core.Authentication;
+import org.springframework.security.authentication.AnonymousAuthenticationToken;
@@
-                if (!(principal instanceof Authentication authentication) || !authentication.isAuthenticated()) {
+                if (!(principal instanceof Authentication authentication)
+                        || !authentication.isAuthenticated()
+                        || authentication instanceof AnonymousAuthenticationToken) {
                     logger.warn("Security Alert: Blocked subscription attempt without authenticated principal");
                     return null;
                 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/java/com/p2ps/config/RoomSubscriptionInterceptor.java` around lines
47 - 49, The subscription guard in RoomSubscriptionInterceptor currently checks
that principal is an Authentication and authenticated but does not explicitly
reject AnonymousAuthenticationToken; add an additional defensive check to treat
AnonymousAuthenticationToken as unauthenticated by updating the conditional that
inspects principal (used where principal and Authentication are referenced) to
also return null if principal is an instance of
org.springframework.security.authentication.AnonymousAuthenticationToken,
ensuring the method (same block that previously returned null) continues to log
the warning and exit when anonymous auth appears in the future.
src/main/java/com/p2ps/config/StompJwtAuthInterceptor.java (2)

61-71: Consider simplifying header lookup with a loop.

The sequential null checks for different header names can be simplified.

♻️ Suggested simplification
     private String resolveToken(StompHeaderAccessor accessor) {
-        String headerToken = accessor.getFirstNativeHeader("Authorization");
-        if (headerToken == null) {
-            headerToken = accessor.getFirstNativeHeader("authorization");
-        }
-        if (headerToken == null) {
-            headerToken = accessor.getFirstNativeHeader("token");
-        }
-        if (headerToken == null) {
-            headerToken = accessor.getFirstNativeHeader("access_token");
-        }
+        String headerToken = Stream.of("Authorization", "authorization", "token", "access_token")
+                .map(accessor::getFirstNativeHeader)
+                .filter(Objects::nonNull)
+                .findFirst()
+                .orElse(null);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/java/com/p2ps/config/StompJwtAuthInterceptor.java` around lines 61 -
71, In resolveToken(StompHeaderAccessor), replace the repeated null-checks for
different header names by iterating a list/array of candidate header keys (e.g.,
"Authorization", "authorization", "token", "access_token") and returning the
first non-null value; update the method to loop through these keys calling
accessor.getFirstNativeHeader(key) and return when a non-null token is found,
otherwise continue to null return — this keeps the lookup concise and preserves
current behavior while centralizing the header list for easy future changes.

86-97: Duplicate extractBearerToken implementation.

This method duplicates JwtAuthFilter.extractBearerToken(). Consider reusing the existing method to maintain consistency and reduce duplication.

♻️ Proposed fix
-    private String extractBearerToken(String authorizationHeader) {
-        if (authorizationHeader == null || authorizationHeader.isBlank()) {
-            return null;
-        }
-
-        String token = authorizationHeader.trim();
-        if (token.regionMatches(true, 0, "Bearer ", 0, 7)) {
-            return token.substring(7).trim();
-        }
-
-        return token;
-    }

Then update resolveToken to use jwtAuthFilter.extractBearerToken(headerToken):

         if (headerToken != null) {
-            return extractBearerToken(headerToken);
+            return jwtAuthFilter.extractBearerToken(headerToken);
         }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/java/com/p2ps/config/StompJwtAuthInterceptor.java` around lines 86 -
97, The extractBearerToken in StompJwtAuthInterceptor duplicates logic already
present in JwtAuthFilter.extractBearerToken; remove the duplicate method and
call the existing JwtAuthFilter.extractBearerToken(...) instead (inject or use
the existing jwtAuthFilter instance) from StompJwtAuthInterceptor.resolveToken
where headerToken is processed so token extraction is delegated to
JwtAuthFilter.extractBearerToken and duplication is eliminated.
src/main/java/com/p2ps/config/WebSocketConfig.java (1)

27-38: Javadoc is outdated.

The constructor Javadoc only documents subscriptionInterceptor but now accepts three interceptors. Update it to reflect all parameters.

📝 Suggested Javadoc update
     /**
-     * Constructor injection for the subscription security interceptor.
-     * `@param` subscriptionInterceptor the interceptor validating inbound traffic
+     * Constructor injection for WebSocket interceptors.
+     * `@param` jwtHandshakeInterceptor validates JWT tokens during WebSocket handshake
+     * `@param` stompJwtAuthInterceptor authenticates STOMP CONNECT frames using JWT
+     * `@param` subscriptionInterceptor validates room subscription requests
      */
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/java/com/p2ps/config/WebSocketConfig.java` around lines 27 - 38, The
constructor Javadoc for WebSocketConfig is outdated and only documents
subscriptionInterceptor; update the Javadoc block above the WebSocketConfig(...)
constructor to list and describe all three parameters (JwtHandshakeInterceptor
jwtHandshakeInterceptor, StompJwtAuthInterceptor stompJwtAuthInterceptor, and
RoomSubscriptionInterceptor subscriptionInterceptor), ensuring each `@param` tag
accurately describes the role of that interceptor in the constructor.
src/test/java/com/p2ps/auth/security/SecurityConfigTest.java (1)

50-67: CORS test has hardcoded expected values.

The test asserts specific CORS configuration values (e.g., http://localhost:5173). While this provides regression protection, consider adding a comment noting these values must stay in sync with SecurityConfig, or extract them as constants shared between production code and tests.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/test/java/com/p2ps/auth/security/SecurityConfigTest.java` around lines 50
- 67, The test corsConfigurationSource_ConfiguredCorrectly in SecurityConfigTest
hardcodes CORS values that must match SecurityConfig.corsConfigurationSource;
either add a concise comment in the test referencing
SecurityConfig.corsConfigurationSource to warn future editors that these
expected values must stay in sync, or better: extract the hardcoded values into
public constants on SecurityConfig (e.g., ALLOWED_ORIGINS, ALLOWED_METHODS,
ALLOWED_HEADERS, ALLOW_CREDENTIALS) and use those constants in the test when
asserting (via SecurityConfig.ALLOWED_ORIGINS, etc.) so the production
configuration and test expectations remain synchronized.
src/test/java/com/p2ps/auth/security/JwtAuthFilterTest.java (1)

218-231: Assert filter-chain continuation in this path as well.

Line 218-231 validates authentication state but does not assert that the request continues down the chain. Add verify(filterChain).doFilter(request, response) for parity with the other doFilterInternal tests.

Suggested assertion add-on
         jwtAuthFilter.doFilterInternal(request, response, filterChain);

         assertNotNull(SecurityContextHolder.getContext().getAuthentication());
         assertEquals("test@test.com", SecurityContextHolder.getContext().getAuthentication().getPrincipal());
+        verify(filterChain).doFilter(request, response);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/test/java/com/p2ps/auth/security/JwtAuthFilterTest.java` around lines 218
- 231, The test method bareTokenWithoutBearerPrefix in JwtAuthFilterTest asserts
authentication but doesn't verify the filter chain was continued; update this
test to also verify the chain by adding a verification that
filterChain.doFilter(request, response) was called (i.e., call
verify(filterChain).doFilter(request, response)) after the existing assertions
so this path mirrors the other doFilterInternal tests.
src/test/java/com/p2ps/config/StompJwtAuthInterceptorTest.java (1)

45-60: Avoid stubbing authenticateToken(null) in no-token cases; verify no auth call instead.

These tests currently pass even if the interceptor incorrectly invokes authentication with null. Prefer asserting verify(jwtAuthFilter, never()).authenticateToken(any()) in no-token paths.

Also applies to: 170-203

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/test/java/com/p2ps/config/StompJwtAuthInterceptorTest.java` around lines
45 - 60, Update the test preSend_ConnectWithoutTokenPassesThrough to assert that
JwtAuthFilter.authenticateToken is never called rather than stubbing
authenticateToken(null); specifically, remove the
when(jwtAuthFilter.authenticateToken(null)) stub and add verify(jwtAuthFilter,
never()).authenticateToken(any()) after calling StompJwtAuthInterceptor.preSend,
referencing JwtAuthFilter.authenticateToken and StompJwtAuthInterceptor.preSend
to locate the code; apply the same change pattern to the other tests noted
(lines ~170-203) that handle "no-token" scenarios so they verify no
authentication invocation instead of stubbing null.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.github/workflows/build.yml:
- Around line 16-20: CI JDK version (the "Set up JDK 21" step with java-version:
21) is mismatched with the Gradle toolchain target (Java 25 in
build.gradle.kts); either update the workflow step to use java-version: 25 to
match the Gradle toolchain, or change the Gradle toolchain JavaLanguageVersion
(the toolchain block / languageVersion.set(JavaLanguageVersion.of(25))) to 21 so
both match—pick one approach and make the corresponding change so the CI
java-version and Gradle toolchain value are identical.

In `@src/main/resources/application.properties`:
- Line 8: The property key spring.data.mongodb.uri in application.properties is
using the old Spring Boot namespace; update it to the Boot 4.0+ format by
replacing the key spring.data.mongodb.uri with spring.mongodb.uri while keeping
the same connection value (e.g.,
mongodb://localhost:27017/${MONGO_DB:p2p_shopping_mongo}) so the app reads the
Mongo URI correctly under Spring Boot 4+.

In `@src/test/java/com/p2ps/auth/security/JwtAuthFilterTest.java`:
- Around line 79-81: The test currently asserts that
jwtAuthFilter.extractBearerToken("Bearer ") returns "Bearer", which accepts a
whitespace-only credential; change the test in JwtAuthFilterTest to assert that
extractBearerToken returns null for inputs like "Bearer " (use assertNull). Also
update the implementation of extractBearerToken in the JwtAuthFilter class so
that after stripping the "Bearer" prefix it trims the credential and returns
null when the remaining token is empty or only whitespace, ensuring malformed
"Bearer" headers are rejected.

In `@src/test/java/resources/application-test.properties`:
- Around line 14-15: Replace the legacy property key and env var usage by
updating occurrences of spring.data.mongodb.uri and SPRING_DATA_MONGODB_URI to
the Spring Boot 4.0 names: spring.mongodb.uri and SPRING_MONGODB_URI;
specifically, update the property key (spring.data.mongodb.uri ->
spring.mongodb.uri) and the environment variable placeholder
(SPRING_DATA_MONGODB_URI -> SPRING_MONGODB_URI) wherever they appear (including
the test and main application properties) so the MongoDB URI is read correctly
under Spring Boot 4.0.4.

---

Nitpick comments:
In `@src/main/java/com/p2ps/config/RoomSubscriptionInterceptor.java`:
- Around line 47-49: The subscription guard in RoomSubscriptionInterceptor
currently checks that principal is an Authentication and authenticated but does
not explicitly reject AnonymousAuthenticationToken; add an additional defensive
check to treat AnonymousAuthenticationToken as unauthenticated by updating the
conditional that inspects principal (used where principal and Authentication are
referenced) to also return null if principal is an instance of
org.springframework.security.authentication.AnonymousAuthenticationToken,
ensuring the method (same block that previously returned null) continues to log
the warning and exit when anonymous auth appears in the future.

In `@src/main/java/com/p2ps/config/StompJwtAuthInterceptor.java`:
- Around line 61-71: In resolveToken(StompHeaderAccessor), replace the repeated
null-checks for different header names by iterating a list/array of candidate
header keys (e.g., "Authorization", "authorization", "token", "access_token")
and returning the first non-null value; update the method to loop through these
keys calling accessor.getFirstNativeHeader(key) and return when a non-null token
is found, otherwise continue to null return — this keeps the lookup concise and
preserves current behavior while centralizing the header list for easy future
changes.
- Around line 86-97: The extractBearerToken in StompJwtAuthInterceptor
duplicates logic already present in JwtAuthFilter.extractBearerToken; remove the
duplicate method and call the existing JwtAuthFilter.extractBearerToken(...)
instead (inject or use the existing jwtAuthFilter instance) from
StompJwtAuthInterceptor.resolveToken where headerToken is processed so token
extraction is delegated to JwtAuthFilter.extractBearerToken and duplication is
eliminated.

In `@src/main/java/com/p2ps/config/WebSocketConfig.java`:
- Around line 27-38: The constructor Javadoc for WebSocketConfig is outdated and
only documents subscriptionInterceptor; update the Javadoc block above the
WebSocketConfig(...) constructor to list and describe all three parameters
(JwtHandshakeInterceptor jwtHandshakeInterceptor, StompJwtAuthInterceptor
stompJwtAuthInterceptor, and RoomSubscriptionInterceptor
subscriptionInterceptor), ensuring each `@param` tag accurately describes the role
of that interceptor in the constructor.

In `@src/test/java/com/p2ps/auth/security/JwtAuthFilterTest.java`:
- Around line 218-231: The test method bareTokenWithoutBearerPrefix in
JwtAuthFilterTest asserts authentication but doesn't verify the filter chain was
continued; update this test to also verify the chain by adding a verification
that filterChain.doFilter(request, response) was called (i.e., call
verify(filterChain).doFilter(request, response)) after the existing assertions
so this path mirrors the other doFilterInternal tests.

In `@src/test/java/com/p2ps/auth/security/SecurityConfigTest.java`:
- Around line 50-67: The test corsConfigurationSource_ConfiguredCorrectly in
SecurityConfigTest hardcodes CORS values that must match
SecurityConfig.corsConfigurationSource; either add a concise comment in the test
referencing SecurityConfig.corsConfigurationSource to warn future editors that
these expected values must stay in sync, or better: extract the hardcoded values
into public constants on SecurityConfig (e.g., ALLOWED_ORIGINS, ALLOWED_METHODS,
ALLOWED_HEADERS, ALLOW_CREDENTIALS) and use those constants in the test when
asserting (via SecurityConfig.ALLOWED_ORIGINS, etc.) so the production
configuration and test expectations remain synchronized.

In `@src/test/java/com/p2ps/config/StompJwtAuthInterceptorTest.java`:
- Around line 45-60: Update the test preSend_ConnectWithoutTokenPassesThrough to
assert that JwtAuthFilter.authenticateToken is never called rather than stubbing
authenticateToken(null); specifically, remove the
when(jwtAuthFilter.authenticateToken(null)) stub and add verify(jwtAuthFilter,
never()).authenticateToken(any()) after calling StompJwtAuthInterceptor.preSend,
referencing JwtAuthFilter.authenticateToken and StompJwtAuthInterceptor.preSend
to locate the code; apply the same change pattern to the other tests noted
(lines ~170-203) that handle "no-token" scenarios so they verify no
authentication invocation instead of stubbing null.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e9007215-d55a-4c04-9b6f-c77e01056aac

📥 Commits

Reviewing files that changed from the base of the PR and between 2fef06c and 87f2f13.

📒 Files selected for processing (20)
  • .env.example
  • .github/workflows/build.yml
  • .github/workflows/test.yml
  • build.gradle.kts
  • docker-compose.yml
  • src/main/java/com/p2ps/auth/security/JwtAuthFilter.java
  • src/main/java/com/p2ps/auth/security/SecurityConfig.java
  • src/main/java/com/p2ps/config/JwtHandshakeInterceptor.java
  • src/main/java/com/p2ps/config/RoomSubscriptionInterceptor.java
  • src/main/java/com/p2ps/config/StompJwtAuthInterceptor.java
  • src/main/java/com/p2ps/config/WebSocketConfig.java
  • src/main/resources/application.properties
  • src/test/java/com/p2ps/auth/JwtAuthFilterTest.java
  • src/test/java/com/p2ps/auth/security/JwtAuthFilterTest.java
  • src/test/java/com/p2ps/auth/security/SecurityConfigTest.java
  • src/test/java/com/p2ps/config/JwtHandshakeInterceptorTest.java
  • src/test/java/com/p2ps/config/RoomSubscriptionInterceptorTest.java
  • src/test/java/com/p2ps/config/StompJwtAuthInterceptorTest.java
  • src/test/java/com/p2ps/config/WebSocketConfigTest.java
  • src/test/java/resources/application-test.properties
💤 Files with no reviewable changes (1)
  • src/test/java/com/p2ps/auth/JwtAuthFilterTest.java

Comment on lines +16 to +20
- name: Set up JDK 21
uses: actions/setup-java@v4
with:
java-version: 17
distribution: 'zulu' # Alternative distribution options are available
java-version: 21
distribution: 'temurin'
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify Java version alignment between workflow and Gradle toolchain
rg -n 'java-version:\s*[0-9]+' .github/workflows/build.yml
rg -n 'JavaLanguageVersion\.of\([0-9]+\)' build.gradle.kts

Repository: P2P-Shopping/server

Length of output: 148


Align CI JDK version with Gradle toolchain target.

CI workflow uses Java 21 (line 19) but build.gradle.kts targets Java 25 (line 15). Update the workflow to use Java 25 or update the Gradle toolchain to match Java 21 to maintain consistency and avoid build inconsistencies.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.github/workflows/build.yml around lines 16 - 20, CI JDK version (the "Set
up JDK 21" step with java-version: 21) is mismatched with the Gradle toolchain
target (Java 25 in build.gradle.kts); either update the workflow step to use
java-version: 25 to match the Gradle toolchain, or change the Gradle toolchain
JavaLanguageVersion (the toolchain block /
languageVersion.set(JavaLanguageVersion.of(25))) to 21 so both match—pick one
approach and make the corresponding change so the CI java-version and Gradle
toolchain value are identical.

spring.datasource.username=${POSTGRES_USER}
spring.datasource.password=${POSTGRES_PASSWORD}
spring.datasource.driver-class-name=org.postgresql.Driver
spring.data.mongodb.uri=mongodb://localhost:27017/${MONGO_DB:p2p_shopping_mongo}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash

# Find build files (pom.xml, build.gradle, etc.)
echo "=== Finding build configuration files ==="
find . -type f \( -name "pom.xml" -o -name "build.gradle" -o -name "build.gradle.kts" \) | head -20

# Check application.properties file
echo -e "\n=== Checking application.properties ==="
if [ -f "src/main/resources/application.properties" ]; then
  cat -n src/main/resources/application.properties
else
  echo "File not found at expected location"
  find . -name "application.properties" -type f
fi

Repository: P2P-Shopping/server

Length of output: 996


🏁 Script executed:

#!/bin/bash

# Check Spring Boot version in build.gradle.kts
echo "=== Checking Spring Boot version in build.gradle.kts ==="
cat -n build.gradle.kts | head -50

# Also search for specific Spring Boot version declaration
echo -e "\n=== Searching for Spring Boot version ==="
grep -n "spring.boot\|SpringBoot\|version" build.gradle.kts | head -20

Repository: P2P-Shopping/server

Length of output: 3229


Update MongoDB connection property to Boot 4.0+ format.

Line 8 uses the legacy spring.data.mongodb.uri prefix. Spring Boot 4.0+ renamed this to spring.mongodb.uri without the .data segment.

Proposed fix
-spring.data.mongodb.uri=mongodb://localhost:27017/${MONGO_DB:p2p_shopping_mongo}
+spring.mongodb.uri=mongodb://localhost:27017/${MONGO_DB:p2p_shopping_mongo}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
spring.data.mongodb.uri=mongodb://localhost:27017/${MONGO_DB:p2p_shopping_mongo}
spring.mongodb.uri=mongodb://localhost:27017/${MONGO_DB:p2p_shopping_mongo}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/resources/application.properties` at line 8, The property key
spring.data.mongodb.uri in application.properties is using the old Spring Boot
namespace; update it to the Boot 4.0+ format by replacing the key
spring.data.mongodb.uri with spring.mongodb.uri while keeping the same
connection value (e.g.,
mongodb://localhost:27017/${MONGO_DB:p2p_shopping_mongo}) so the app reads the
Mongo URI correctly under Spring Boot 4+.

Comment on lines +79 to +81
void bearerWithOnlyWhitespace_ReturnsBearer() {
assertEquals("Bearer", jwtAuthFilter.extractBearerToken("Bearer "));
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Bearer with no credentials should not be treated as a usable token.

Line 80 currently asserts "Bearer " becomes "Bearer", which bakes malformed header handling into the contract. Prefer returning null for empty Bearer credentials so malformed auth headers are rejected cleanly.

Suggested test adjustment
-        void bearerWithOnlyWhitespace_ReturnsBearer() {
-            assertEquals("Bearer", jwtAuthFilter.extractBearerToken("Bearer "));
+        void bearerWithOnlyWhitespace_ReturnsNull() {
+            assertNull(jwtAuthFilter.extractBearerToken("Bearer "));
         }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
void bearerWithOnlyWhitespace_ReturnsBearer() {
assertEquals("Bearer", jwtAuthFilter.extractBearerToken("Bearer "));
}
void bearerWithOnlyWhitespace_ReturnsNull() {
assertNull(jwtAuthFilter.extractBearerToken("Bearer "));
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/test/java/com/p2ps/auth/security/JwtAuthFilterTest.java` around lines 79
- 81, The test currently asserts that jwtAuthFilter.extractBearerToken("Bearer
") returns "Bearer", which accepts a whitespace-only credential; change the test
in JwtAuthFilterTest to assert that extractBearerToken returns null for inputs
like "Bearer " (use assertNull). Also update the implementation of
extractBearerToken in the JwtAuthFilter class so that after stripping the
"Bearer" prefix it trims the credential and returns null when the remaining
token is empty or only whitespace, ensuring malformed "Bearer" headers are
rejected.

Comment on lines +14 to +15
# MongoDB - can be overridden via SPRING_DATA_MONGODB_URI env var for integration tests with real MongoDB
spring.data.mongodb.uri=${SPRING_DATA_MONGODB_URI:mongodb://mock-address:27017/test}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# Find build configuration files to determine Spring Boot version
find . -maxdepth 3 -type f \( -name "pom.xml" -o -name "build.gradle*" \) | head -20

Repository: P2P-Shopping/server

Length of output: 81


🏁 Script executed:

# Check the test properties file mentioned in the review
find . -type f -name "application-test.properties" -o -name "application.properties" | head -10

Repository: P2P-Shopping/server

Length of output: 160


🏁 Script executed:

# Check Spring Boot version in build.gradle.kts
cat build.gradle.kts | grep -A 5 -B 5 -i "boot\|version"

Repository: P2P-Shopping/server

Length of output: 2079


🏁 Script executed:

# Read both properties files to compare MongoDB property usage
echo "=== Main properties ===" && cat src/main/resources/application.properties
echo "" && echo "=== Test properties ===" && cat src/test/java/resources/application-test.properties

Repository: P2P-Shopping/server

Length of output: 1477


🏁 Script executed:

# Search for all MongoDB property usages in the codebase
rg -i "spring\..*mongodb" --type properties -B 1 -A 1

Repository: P2P-Shopping/server

Length of output: 97


🏁 Script executed:

# Search in Java code or other config files for MongoDB URI references
rg -i "mongodb|spring\.data\.mongodb|spring\.mongodb" --type-list | head -20

Repository: P2P-Shopping/server

Length of output: 452


🏁 Script executed:

# Search for all MongoDB property usages in properties files
rg "spring\..*mongodb" . -g "*.properties"

Repository: P2P-Shopping/server

Length of output: 326


🏁 Script executed:

# Search for MongoDB references in Java code to understand usage
rg -i "mongodb\|MongoTemplate\|MongoClient" . -t java | head -30

Repository: P2P-Shopping/server

Length of output: 45


Test Mongo property uses outdated Spring Boot 4.0 prefix—must update to spring.mongodb.uri.

Line 15 uses the legacy spring.data.mongodb.uri key, which is not recognized in Spring Boot 4.0.4. Update to the new property prefix and corresponding environment variable name to ensure the MongoDB URI configuration is applied correctly.

Proposed fix
-# MongoDB - can be overridden via SPRING_DATA_MONGODB_URI env var for integration tests with real MongoDB
-spring.data.mongodb.uri=${SPRING_DATA_MONGODB_URI:mongodb://mock-address:27017/test}
+# MongoDB - can be overridden via SPRING_MONGODB_URI env var for integration tests with real MongoDB
+spring.mongodb.uri=${SPRING_MONGODB_URI:mongodb://mock-address:27017/test}

Note: The same issue exists in src/main/resources/application.properties line 8 and should be corrected there as well.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# MongoDB - can be overridden via SPRING_DATA_MONGODB_URI env var for integration tests with real MongoDB
spring.data.mongodb.uri=${SPRING_DATA_MONGODB_URI:mongodb://mock-address:27017/test}
# MongoDB - can be overridden via SPRING_MONGODB_URI env var for integration tests with real MongoDB
spring.mongodb.uri=${SPRING_MONGODB_URI:mongodb://mock-address:27017/test}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/test/java/resources/application-test.properties` around lines 14 - 15,
Replace the legacy property key and env var usage by updating occurrences of
spring.data.mongodb.uri and SPRING_DATA_MONGODB_URI to the Spring Boot 4.0
names: spring.mongodb.uri and SPRING_MONGODB_URI; specifically, update the
property key (spring.data.mongodb.uri -> spring.mongodb.uri) and the environment
variable placeholder (SPRING_DATA_MONGODB_URI -> SPRING_MONGODB_URI) wherever
they appear (including the test and main application properties) so the MongoDB
URI is read correctly under Spring Boot 4.0.4.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant